<!DOCTYPE html>
<%@ taglib prefix="s" uri="/struts-tags"%>
<s:set var="ok" value="%{getText(\"button.ok\")}" />
<s:set var="cancel" value="%{getText(\"button.cancel\")}" />
<s:set var="createSuccessfulMsg"
  value="%{getText('info.create.successful', {getText('title.customer.customerProfile')})}" />
<s:set var="requiredMsg" value="%{getText('error.required')}" />
<link href="${pageContext.request.contextPath}/css/jquery-ui-combobox.custom.css" rel="stylesheet"
  type="text/css" />
<script type="text/javascript">
  function loadCity(region) {
    jQuery.ajax({
      url : '${pageContext.request.contextPath}/district/getCities.action',
      dataType : 'json',
      cache : true,
      data : {
        region : region
      },
      success : function(data) {
        var city = $('#city');
        city.empty();
        $('#city_combobox').val('');
        $.each(data.rows,function(idx,record) {
          city.append($('<option />').val(record.id).text(record.name));
        });
      }
    });
  }

  function loadRegion() {
    jQuery.ajax({
      url : '${pageContext.request.contextPath}/district/getRegions.action',
      dataType : 'json',
      cache : true,
      success : function(data) {
        var region = $('#region');
        region.empty();
        $.each(data.rows,function(idx,record) {
          region.append($('<option />').val(record.id).text(record.name));
        });
      }
    });
  }

  function resetForm() {
    $('#dialog-form :input').val('');
    focusOnFirstElement();
  }

  function focusOnFirstElement() {
<%-- we need to set some delay due to bug (delay in rendering) in IE  --%>
  setTimeout(function() {
      $('#dialog-form :input:visible:enabled:first').focus();
    },10);
  }

  $(function() {
    $('#customerMsg').tooltip({
      tooltipClass : "ui-state-highlight"
    });
    loadRegion();
    $("#dialog-form").dialog({
      height : 540,
      width : 800,
      modal : true,
      buttons : {
        '<s:property value="#ok" />' : function() {
          var bValid = $('#customer-form').valid();
          if (bValid) {
            jQuery.ajax({
              url : '${pageContext.request.contextPath}/customer/createCustomer.action',
              type : 'POST',
              dataType : 'json',
              cache : false,
              data : {
                'customer.firstname' : $('#firstname').val(),
                'customer.lastname' : $('#lastname').val(),
                'customer.alias' : $('#alias').val(),
                'customer.phone' : $('#phone').val(),
                'customer.mobile' : $('#mobile').val(),
                'customer.fax' : $('#fax').val(),
                'customer.email' : $('#email').val(),
                'customer.street' : $('#street').val(),
                'customer.postalCode' : $('#postalCode').val(),
                'customer.city.id' : $('#city option:selected').val()
              },
              success : function(data) {
                var msg = '';
                var status = data.status;
                if (status == 'SUCCESS') {
                  msg = '<s:property value="#createSuccessfulMsg"/>';
<%-- reload parent customer list --%>
  $('#listCustomer').trigger('reloadGrid');
                  resetForm();
                } else if (status == 'ERROR') {
                  if (data.errors) {
                    var errors = data.errors;
                    for ( var i = 0; i < errors.length; i++) {
                      msg += errors[i];
                      if (i < errors.length - 1) {
                        msg += ', ';
                      }
                    }
                  }
                }
                $('#customerMsg').attr('title',msg).tooltip('open');
                setTimeout(function() {
                  $('#customerMsg').tooltip("close").attr("title","");
                },1500);
              }
            });

          }
        },
        '<s:property value="#cancel" />' : function() {
          $(this).remove();
        }
      },
      close : function() {
        $(this).remove();
      }
    });
    $("#customerAccordion").multipleaccordion();
    $("#region").combobox({
      error : function() {
        $('#city').empty();
      }
    });
    $('#city').combobox();
    $("#region").change(function() {
      var value = $(this).find('option:selected').val();
      if (value != '') {
        loadCity(value);
      }
    });
    $('#customerAccordion > div > table td.LABEL').css({
      'width' : '95px'
    });
    $('input, select, textarea, button').not(':hidden').each(function(idx) {
      $(this).prop('tabindex',idx + 1);
    });
<%-- need to append form on the fly after rendering dialog otherwise, form will be removed --%>
  $('#dialog-form').wrap('<form id="customer-form">');
    $.validator.setDefaults({
      errorClass : 'ui-state-error',
      errorPlacement : function(error,element) {
        if (element.context.id.indexOf('_combobox') == -1) {
          error.insertAfter(element.parent().children(':last'));
        } else {
          error.appendTo(element.parent());
        }
      }
    });
    $('#customer-form').validate(
        {
          rules : {
            'customer.firstname' : {
              required : true
            },
            'customer.alias' : {
              required : true,
              minlength : 3
            },
            'customer.phone' : {
              required : true
            },
            'customer.mobile' : {
              required : true
            },
            'customer.street' : {
              required : true
            },
            'region_combobox' : {
              required : true
            },
            'city_combobox' : {
              required : true
            }
          },
          messages : {
            'customer.firstname' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.firstname\")}" />')
            },
            'customer.alias' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.customer.alias\")}" />'),
              minlength : jQuery.format('<s:property value="getText(\"error.minLength\")" />',
                  '<s:property value="%{getText(\"field.customer.alias\")}" />',3)
            },
            'customer.phone' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.phone\")}" />')
            },
            'customer.mobile' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.mobile\")}" />')
            },
            'customer.street' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.street\")}" />')
            },
            'region_combobox' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.region\")}" />')
            },
            'city_combobox' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.city\")}" />')
            }
          }
        });
    focusOnFirstElement();
  });
</script>
<div id="dialog-form" title='<s:property value="getText('title.add.customer')"/>'>
  <div id="customerMsg"></div>
  <div id="customerAccordion">
    <h3>
      <s:property value="getText('title.customer.details')" />
    </h3>
    <div>
      <table>
        <tr>
          <td class="LABEL"><label for="firstname" class="mandatory"><s:property
                value="getText('field.contact.name')" /></label></td>
          <td><input type="text" id="firstname" name="customer.firstname"
            placeholder="<s:property
								value="getText('field.firstname')" />"> <input
            type="text" id="lastname" name="customer.lastname"
            placeholder="<s:property
								value="getText('field.lastname')" />"></td>
        </tr>
        <tr>
          <td class="LABEL"><label for="alias" class="mandatory"><s:property
                value="getText('field.customer.alias')" /></label>
          <td><input type="text" id="alias" name="customer.alias"></td>
        </tr>
      </table>
    </div>
    <h3>
      <s:property value="getText('title.contact.information')" />
    </h3>
    <div>
      <table>
        <tr>
          <td class="LABEL"><label for="phone" class="mandatory"><s:property
                value="getText('field.phone')" /></label></td>
          <td><input type="text" id="phone" name="customer.phone"></td>
        </tr>
        <tr>
          <td class="LABEL"><label for="mobile" class="mandatory"><s:property
                value="getText('field.mobile')" /></label></td>
          <td><input type="text" id="mobile" name="customer.mobile"></td>
        </tr>
        <tr>
          <td class="LABEL"><label for="fax"><s:property value="getText('field.fax')" /></label></td>
          <td><input type="text" id="fax" name="customer.fax"></td>
        </tr>
        <tr>
          <td class="LABEL"><label for="email"><s:property
                value="getText('field.email')" /></label></td>
          <td><input type="text" id="email" name="customer.email"></td>
        </tr>
      </table>
    </div>
    <h3>
      <s:property value="getText('title.address')" />
    </h3>
    <div>
      <table>
        <tr>
          <td class="LABEL"><label for="street" class="mandatory"><s:property
                value="getText('field.street')" /></label></td>
          <td><textarea cols="30" rows="5" id="street" name="customer.street"></textarea></td>
        </tr>
        <tr>
          <td class="LABEL"><label for="postalCode"><s:property
                value="getText('field.postalCode')" /></label></td>
          <td><input type="text" id="postalCode" name="customer.postalCode"></td>
        </tr>
        <tr>
          <td><label for="region" class="mandatory"><s:property
                value="getText('field.region')" /></label></td>
          <td><select id="region" name="customer.region"></select></td>
        </tr>
        <tr>
          <td class="LABEL"><label for="city" class="mandatory"><s:property
                value="getText('field.city')" /></label></td>
          <td><select id="city" name="customer.city"></select></td>
        </tr>
      </table>
    </div>
  </div>
</div>
